package cn.itsource.ymcc.listener;

import cn.itsource.ymcc.domain.PayFlow;
import cn.itsource.ymcc.domain.PayOrder;
import cn.itsource.ymcc.dto.PayResultDto;
import cn.itsource.ymcc.service.IPayOrderService;
import cn.itsource.ymcc.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;

import java.nio.charset.StandardCharsets;
import java.util.Map;

@RocketMQTransactionListener(txProducerGroup = "alipayGroup")
public class PayListener implements RocketMQLocalTransactionListener {
    @Autowired
    private IPayOrderService payOrderService;
    //执行本地事务
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            AssertUtil.isNotNull(o,"订单无效");
            Map<String,Object> map = (Map<String,Object>)o;
            PayOrder payOrder = (PayOrder)map.get("payOrder");
            PayFlow payFlow = (PayFlow)map.get("payFlow");
            payOrderService.updateOrderAndFlow(payFlow,payOrder);

            return RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e){
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }

    }
    //检查本地事务
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            byte[] bytes = (byte[])message.getPayload();
            String s = new String(bytes, StandardCharsets.UTF_8);
            PayResultDto payResultDto = JSON.parseObject(s, PayResultDto.class);
            String orderNo = payResultDto.getOrderNo();
            PayOrder payOrder = payOrderService.selectByOrderNo(orderNo);
            boolean localSuccess = payOrder.getPayStatus() != 0;
            return localSuccess ? RocketMQLocalTransactionState.COMMIT : RocketMQLocalTransactionState.ROLLBACK;
        }catch (Exception e){
            e.printStackTrace();
            return RocketMQLocalTransactionState.UNKNOWN;
        }

    }


}
